import os
import logging
from pathlib import Path
from typing import List, Optional
from source.RFT.utils import parse_folder_name, load_details_json, logger

def scan_scenario_folders(input_dir: str) -> List[str]:
    """
    扫描输入目录下的所有故障场景文件夹
    
    参数:
        input_dir: 输入目录路径
        
    返回:
        有效场景文件夹的完整路径列表
    """
    logger.info(f"开始扫描场景文件夹: {input_dir}")
    
    input_path = Path(input_dir)
    if not input_path.exists():
        logger.error(f"输入目录不存在: {input_dir}")
        return []
    
    valid_folders = []
    total_folders = 0
    
    # 遍历输入目录下的所有子目录
    for item in input_path.iterdir():
        if not item.is_dir():
            continue
            
        total_folders += 1
        folder_path = str(item)
        folder_name = item.name
        
        # 检查必要文件是否存在
        cache_file = item / "cache" / "telemetry_loader.pkl"
        results_file = item / "detection_results" / "trace_anomalies" / "trace_results" / "results.json"
        details_file = item / "details.json"
        
        if not cache_file.exists():
            logger.warning(f"跳过文件夹 {folder_name}: 缺少缓存文件 {cache_file}")
            continue
            
        if not results_file.exists():
            logger.warning(f"跳过文件夹 {folder_name}: 缺少结果文件 {results_file}")
            continue
        
        details = load_details_json(folder_path)
        if details and "anomaly_details" in details:
            anomaly_details = details["anomaly_details"]
            if "component" in anomaly_details and "reason" in anomaly_details:
                valid_scenario = True
                logger.info(f"从details.json中获取故障信息: 组件={anomaly_details['component']}, 类型={anomaly_details['reason']}")
    
        if valid_scenario:
            valid_folders.append(folder_path)
    
    logger.info(f"场景扫描完成: 总文件夹数 {total_folders}, 有效场景数 {len(valid_folders)}")
    
    return valid_folders
